import { FormField, FieldRenderer } from '../types'
import { escapeForHtml, generateRequiredAttr, generatePlaceholderAttr } from '../utils/htmlUtils'

export class TagsFieldRenderer implements FieldRenderer {
  render(field: FormField): string {
    const maxTags = field.maxTags || 6
    const requiredAttr = generateRequiredAttr(field.required)
    const placeholder = generatePlaceholderAttr(field.placeholder)

    return `
      <div class="form-group">
          <label class="form-label" for="${field.id}">
            ${escapeForHtml(field.label)} ${field.required ? '*' : ''}
            <span class="tag-counter">(0/${maxTags})</span>
          </label>
          <div class="tag-input-container" data-field-id="${field.id}" data-max-tags="${maxTags}">
              <div class="tag-display" id="${field.id}-display"></div>
              <input 
                  type="text" 
                  id="${field.id}-input"
                  class="tag-input"
                  ${placeholder}
                  maxlength="20"
              />
          </div>
          <input type="hidden" id="${field.id}" name="${field.id}" ${requiredAttr} />
          ${field.hint ? `<div class="tag-hint">${escapeForHtml(field.hint)}</div>` : ''}
      </div>
    `
  }

  getValidationScript(field: FormField): string {
    return `
      const ${field.id}Input = document.getElementById('${field.id}');
      const ${field.id} = ${field.id}Input ? JSON.parse(${field.id}Input.value || '[]') : [];
      formData.${field.id} = ${field.id};
      log('${field.label}数量: ' + ${field.id}.length);
      ${field.required ? `if (${field.id}.length === 0) { isValid = false; }` : ''}
    `
  }

  generateScript(field: FormField): string {
    const maxTags = field.maxTags || 6
    const initialTags = Array.isArray(field.value) ? field.value : []
    const tagsJson = JSON.stringify(initialTags)

    return `
      // 初始化标签组件 ${field.id}
      (function() {
        const container = document.querySelector('[data-field-id="${field.id}"]');
        const display = document.getElementById('${field.id}-display');
        const input = document.getElementById('${field.id}-input');
        const hidden = document.getElementById('${field.id}');
        const maxTags = ${maxTags};
        const initialTags = ${tagsJson};
        let currentTags = [...initialTags];
        
        // HTML 转义函数
        function escapeHtml(text) {
          if (!text) return '';
          const div = document.createElement('div');
          div.textContent = text;
          return div.innerHTML;
        }
        
        // 更新标签显示
        function updateTagDisplay() {
          display.innerHTML = currentTags.map((tag, index) => 
            '<span class="tag-item">' + 
              '<span class="tag-text">' + escapeHtml(tag) + '</span>' +
              '<span class="tag-remove" onclick="removeTag_${field.id}(' + index + ')">×</span>' +
            '</span>'
          ).join('');
          
          // 更新隐藏字段
          hidden.value = JSON.stringify(currentTags);
          
          // 更新计数器
          const counter = container.parentElement.querySelector('.tag-counter');
          if (counter) {
            counter.textContent = '(' + currentTags.length + '/' + maxTags + ')';
          }
          
          // 更新输入框状态
          input.disabled = currentTags.length >= maxTags;
          if (input.disabled) {
            input.placeholder = '已达到标签上限';
          } else {
            input.placeholder = '${field.placeholder || '输入标签后按回车'}';
          }
        }
        
        // 添加标签
        function addTag(tagText) {
          const tag = tagText.trim();
          if (!tag) return false;
          
          if (tag.length > 20) {
            alert('标签长度不能超过20个字符');
            return false;
          }
          
          if (!/^[\\u4e00-\\u9fa5a-zA-Z0-9_-]+$/.test(tag)) {
            alert('标签只能包含中文、英文、数字、下划线和连字符');
            return false;
          }
          
          if (currentTags.includes(tag)) {
            alert('标签已存在');
            return false;
          }
          
          if (currentTags.length >= maxTags) {
            alert('最多只能添加' + maxTags + '个标签');
            return false;
          }
          
          currentTags.push(tag);
          updateTagDisplay();
          return true;
        }
        
        // 删除标签
        window.removeTag_${field.id} = function(index) {
          currentTags.splice(index, 1);
          updateTagDisplay();
        };
        
        // 输入框事件
        input.addEventListener('keydown', function(e) {
          if (e.key === 'Enter' || e.key === ',') {
            e.preventDefault();
            if (addTag(input.value)) {
              input.value = '';
            }
          }
        });
        
        input.addEventListener('blur', function() {
          if (input.value.trim()) {
            if (addTag(input.value)) {
              input.value = '';
            }
          }
        });
        
        // 初始化显示
        updateTagDisplay();
      })();
    `
  }
}
